package com.timmy.bluetooth.bluetoothData;

import android.os.Handler;

import com.timmy.bluetooth.utils.DebugLog;


/**
 * 解析来自 蓝牙接受的数据
 * Created by sandy on 16/5/7.
 */
public class DataParse {

    final static byte BATTERY_HEAD = (byte) 0xcd;               //电量
    final static byte STATUS_HEAD = (byte) 0xab;
    final static byte STATUS_CHARGE_HEAD = (byte) 0xcf;

    private byte[] data;
    private OnBackDataListener dataListener;
    private Handler handler;

    public DataParse() {
        handler = new Handler();

    }

    public void setOnBaseShockCompleteListener(OnBackDataListener dataListener) {
        this.dataListener = dataListener;
        lastBaat = 0;
    }

    byte lastBaat = 0;

    private byte getBatteryValue(byte[] dat) {
        int Adc_value = ((dat[3] << 8 | (dat[4] < 0 ? dat[4] + 256 : dat[4])) & 0x0fff) >> 1;

        int max = 3110 >> 1;
        int min = 2580 >> 1;


        byte baat = (byte) ((Adc_value - min) / ((max - min) * 1.0f) * 100);
        if (baat < 0)
            baat = 0;
        if (baat > 100)
            baat = 100;

        byte newBaat = 0;
        if (lastBaat != 0) {
            newBaat = (byte) ((lastBaat + baat) / 2);
        } else {
            newBaat = baat;
        }
        lastBaat = baat;

        return newBaat;
    }

    /**
     * 这里将会显示电量
     *
     * @param data
     */
    public void startParseData(byte[] data) {

        byte head = data[1];

        ReceiveData receiveData = new ReceiveData();

        switch (head) {
            case BATTERY_HEAD:
                byte value = getBatteryValue(data);
                receiveData.setBatteryValue(value);
                break;
            case STATUS_HEAD:
                DebugLog.e("返回动作完成。");
                receiveData.setCompleteAction(true);
                break;
            case STATUS_CHARGE_HEAD:
                break;
        }

        if (dataListener != null) {
            dataListener.onData(receiveData);
        }
    }
}
